'use server';

import { getSession } from '@/lib/auth';
import redis, { genCartKey } from '@/lib/redis';
import { result, withZod } from '@/lib/utils';
import { revalidatePath } from 'next/cache';
import { z } from 'zod';
import { BizError, ErrorCode } from '../error';

export const updateCart = withZod(
  z.object({
    shopId: z.number(),
    productId: z.number(),
    count: z.number().int().min(0),
  }),
  async ({ shopId, productId, count }) => {
    try {
      const session = await getSession();
      if (!session?.user)
        throw new BizError(ErrorCode.Unauthorized, '用户未登录');
      const cartKey = genCartKey(session.user.id, shopId);
      const cartJSON = await redis.get(cartKey);
      const cart = cartJSON ? JSON.parse(cartJSON) : {};
      if (count === 0) {
        delete cart[productId];
      } else {
        cart[productId] = count;
      }
      if (Object.keys(cart).length === 0) await redis.del(cartKey);
      else await redis.setEx(cartKey, 60 * 60 * 24, JSON.stringify(cart));

      revalidatePath(`/detail-shop/${shopId}`);
      revalidatePath(`/detail-shop/product/${productId}`);
      return result();
    } catch (error) {
      return result(error, '加入购物车失败,请重试');
    }
  },
);

export const clearCart = withZod(z.number(), async (shopId) => {
  try {
    const session = await getSession();
    if (!session?.user)
      throw new BizError(ErrorCode.Unauthorized, '用户未登录');
    const cartKey = genCartKey(session.user.id, shopId);
    await redis.del(cartKey);
    return result();
  } catch (error) {
    return result(error, '清空购物车失败,请重试');
  }
});
